package com.crud.application;

import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HBaseService {

    private final Connection connection;

    @Autowired
    public HBaseService(Connection connection) {
        this.connection = connection;
    }

    // 创建表
    public void createTable(String tableName, String[] columnFamilies) throws IOException {
        try (Admin admin = connection.getAdmin()) {
            TableName table = TableName.valueOf(tableName);
            if (!admin.tableExists(table)) {
                HTableDescriptor tableDescriptor = new HTableDescriptor(table);
                for (String cf : columnFamilies) {
                    tableDescriptor.addFamily(new HColumnDescriptor(cf));
                }
                admin.createTable(tableDescriptor);
            }
        }
    }

    // 插入数据
    public void insertData(String tableName, String rowKey, String columnFamily, String qualifier, String value) throws IOException {
        try (Table table = connection.getTable(TableName.valueOf(tableName))) {
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier), Bytes.toBytes(value));
            table.put(put);
        }
    }

    // 获取单条数据
    public Result getData(String tableName, String rowKey) throws IOException {
        try (Table table = connection.getTable(TableName.valueOf(tableName))) {
            Get get = new Get(Bytes.toBytes(rowKey));
            return table.get(get);
        }
    }

    // 获取表中所有数据
    public List<Result> getAllData(String tableName) throws IOException {
        List<Result> results = new ArrayList<>();
        Scan scan = new Scan(); // 将 Scan 对象创建移到 try-with-resources 外部
        try (Table table = connection.getTable(TableName.valueOf(tableName));
             ResultScanner scanner = table.getScanner(scan)) {
            for (Result result : scanner) {
                results.add(result);
            }
        }
        return results;
    }

    // 删除数据
    public void deleteData(String tableName, String rowKey) throws IOException {
        try (Table table = connection.getTable(TableName.valueOf(tableName))) {
            Delete delete = new Delete(Bytes.toBytes(rowKey));
            table.delete(delete);
        }
    }

    // 删除表
    public void deleteTable(String tableName) throws IOException {
        try (Admin admin = connection.getAdmin()) {
            TableName table = TableName.valueOf(tableName);
            if (admin.tableExists(table)) {
                admin.disableTable(table);
                admin.deleteTable(table);
            }
        }
    }
}